// pages/games/wheel/wheel.js
Page({
  data: {
    // 用户数据
    userPoints: 100,
    isSpinning: false,
    
    // 转盘配置
    wheelSegments: [
      { label: '10积分', value: 10, color: '#FF6B6B', probability: 20 },
      { label: '20积分', value: 20, color: '#4ECDC4', probability: 15 },
      { label: '50积分', value: 50, color: '#45B7D1', probability: 10 },
      { label: '100积分', value: 100, color: '#96CEB4', probability: 5 },
      { label: '谢谢参与', value: 0, color: '#FECA57', probability: 30 },
      { label: '再来一次', value: 0, color: '#FF9FF3', probability: 15 },
      { label: '5积分', value: 5, color: '#54A0FF', probability: 5 }
    ],
    
    // 转盘状态
    currentRotation: 0,
    selectedSegment: null,
    
    // 动画状态
    animationClass: '',
    
    // 弹窗控制
    showResultModal: false,
    showNoPointsModal: false,
    resultData: { title: '', message: '', points: 0 },
    
    // 消耗积分
    costPerSpin: 5
  },

  onLoad() {
    this.loadUserData();
    this.generateWheelSegments();
  },

  onShow() {
    this.loadUserData();
  },

  // 加载用户数据 - 统一使用games/index的积分
  loadUserData() {
    const userData = wx.getStorageSync('userData') || {};
    this.setData({
      userPoints: userData.points || 100
    });
  },

  // 保存用户数据 - 保存到统一的userData
  saveUserData() {
    const userData = wx.getStorageSync('userData') || {};
    userData.points = this.data.userPoints;
    wx.setStorageSync('userData', userData);
  },

  // 生成转盘扇形
  generateWheelSegments() {
    const segments = this.data.wheelSegments;
    const totalSegments = segments.length;
    const anglePerSegment = 360 / totalSegments;
    
    const wheelHTML = segments.map((segment, index) => {
      const startAngle = index * anglePerSegment;
      const endAngle = (index + 1) * anglePerSegment;
      const rotation = startAngle + anglePerSegment / 2;
      
      return {
        ...segment,
        startAngle,
        endAngle,
        rotation,
        style: `transform: rotate(${rotation}deg); background-color: ${segment.color};`
      };
    });
    
    this.setData({ processedSegments: wheelHTML });
  },

  // 开始旋转
  startSpin() {
    if (this.data.isSpinning || this.data.userPoints < this.data.costPerSpin) {
      if (this.data.userPoints < this.data.costPerSpin) {
        this.setData({ showNoPointsModal: true });
      }
      return;
    }

    // 扣除积分
    this.setData({
      userPoints: this.data.userPoints - this.data.costPerSpin,
      isSpinning: true
    });
    this.saveUserData();

    // 计算结果
    const result = this.calculateResult();
    const targetRotation = this.calculateTargetRotation(result.segmentIndex);
    
    // 开始动画
    this.animateWheel(targetRotation, result);
  },

  // 根据概率计算结果
  calculateResult() {
    const segments = this.data.wheelSegments;
    const random = Math.random() * 100;
    let cumulativeProbability = 0;
    
    for (let i = 0; i < segments.length; i++) {
      cumulativeProbability += segments[i].probability;
      if (random <= cumulativeProbability) {
        return {
          segmentIndex: i,
          segment: segments[i]
        };
      }
    }
    
    return {
      segmentIndex: 0,
      segment: segments[0]
    };
  },

  // 计算目标旋转角度
  calculateTargetRotation(segmentIndex) {
    const segments = this.data.wheelSegments;
    const anglePerSegment = 360 / segments.length;
    
    // 关键修正：计算转盘需要旋转多少度，使目标扇形中心对准顶部指针
    // 扇形中心角度 = 扇形索引 * 每扇形角度 + 半扇形角度
    const segmentCenterAngle = segmentIndex * anglePerSegment + (anglePerSegment / 2);
    
    // 关键理解：转盘旋转后，目标扇形的中心应该位于顶部（0度位置）
    // 因此转盘需要旋转的角度 = -segmentCenterAngle（负值表示顺时针旋转）
    const rotationToAlign = -segmentCenterAngle;
    
    // 添加多圈旋转（5-7圈），确保顺时针方向
    const fullRotations = 5 + Math.floor(Math.random() * 3);
    
    // 最终旋转角度 = 多圈旋转 + 对齐角度
    const baseRotation = this.data.currentRotation;
    const finalRotation = baseRotation + (fullRotations * 360) + rotationToAlign;
    
    return finalRotation;
  },

  // 动画旋转
  animateWheel(targetRotation, result) {
    // 创建动画实例
    const animation = wx.createAnimation({
      duration: 4000, // 4秒动画
      timingFunction: 'cubic-bezier(0.25, 0.1, 0.25, 1)', // 缓动函数
      delay: 0
    });

    // 设置动画
    animation.rotate(targetRotation).step();
    
    this.setData({
      wheelAnimation: animation.export(),
      isSpinning: true
    });

    // 动画完成后显示结果
    setTimeout(() => {
      // 动画完成后验证结果
      const segments = this.data.wheelSegments;
      const anglePerSegment = 360 / segments.length;
      const finalAngle = targetRotation % 360;
      
      // 关键修正：转盘旋转后，计算哪个扇形中心对准了顶部指针
      // 顶部指针位置为0度，计算每个扇形中心到0度的距离
      
      // 由于转盘顺时针旋转，最终角度为负值
      // 我们需要计算：在旋转后的转盘上，哪个扇形中心最接近顶部
      
      // 方法：计算每个扇形中心在旋转后的位置
      const topPointerAngle = 0; // 顶部指针位置
      
      // 计算每个扇形中心在旋转后的角度位置
      let pointedIndex = -1;
      let minDistance = Infinity;
      
      for (let i = 0; i < segments.length; i++) {
        const segmentCenterAngle = (i * anglePerSegment) + (anglePerSegment / 2);
        // 旋转后的扇形中心角度 = 原始角度 + 旋转角度
        const rotatedCenterAngle = (segmentCenterAngle + finalAngle + 360) % 360;
        
        // 计算到顶部指针的距离（考虑圆形最短距离）
        let distance = Math.abs(rotatedCenterAngle - topPointerAngle);
        if (distance > 180) distance = 360 - distance;
        
        if (distance < minDistance) {
          minDistance = distance;
          pointedIndex = i;
        }
      }
      
      console.log('结果验证:', {
        目标扇形: result.segmentIndex,
        实际指向: pointedIndex,
        最终角度: targetRotation,
        模360角度: finalAngle,
        每扇形角度: anglePerSegment
      });
      
      // 更新当前旋转角度
      this.setData({
        currentRotation: targetRotation,
        isSpinning: false,
        selectedSegment: segments[pointedIndex]
      });
      
      this.showResult(segments[pointedIndex]);
      
    }, 4000);
  },

  // 显示结果
  showResult(segment) {
    let title = '';
    let message = '';
    
    if (segment.value > 0) {
      // 中奖
      title = '🎉 恭喜中奖！';
      message = `您获得了 ${segment.value} 积分`;
      
      // 更新积分
      this.setData({
        userPoints: this.data.userPoints + segment.value
      });
      this.saveUserData();
      
      // 震动反馈
      if (wx.vibrateLong) {
        wx.vibrateLong();
      }
    } else {
      // 未中奖
      if (segment.label === '再来一次') {
        title = '🔄 再来一次！';
        message = '获得一次免费旋转机会';
        
        // 返还积分
        this.setData({
          userPoints: this.data.userPoints + this.data.costPerSpin
        });
        this.saveUserData();
      } else {
        title = '😊 谢谢参与';
        message = '再接再厉，下次一定中奖！';
        
        // 短暂震动
        if (wx.vibrateShort) {
          wx.vibrateShort();
        }
      }
    }
    
    this.setData({
      resultData: { title, message, points: segment.value },
      showResultModal: true
    });
  },

  // 关闭结果弹窗
  closeResultModal() {
    this.setData({
      showResultModal: false,
      selectedSegment: null
    });
  },

  // 关闭积分不足弹窗
  closeNoPointsModal() {
    this.setData({ showNoPointsModal: false });
  },

  // 分享功能
  onShareAppMessage() {
    return {
      title: '来玩幸运大转盘！看看你的手气如何',
      path: '/pages/games/wheel/wheel',
      imageUrl: '/assets/images/wheel-share.jpg'
    };
  }
});